//生成并使用JSON格式的配置文件，使用ArduinoJson库
//文档：https://arduinojson.org/v6/doc/deserialization/
//      https://arduinojson.org/v6/doc/serialization/

#include <ArduinoJson.h>
#include <FS.h>

DynamicJsonDocument cfg(1024);
//json对象的容量可以通过https://arduinojson.org/v6/assistant/计算得到
//DynamicJsonDocument对象存放在堆空间

bool loadConfig() {
    File configFile = SPIFFS.open("/config.json", "r");//打开配置文件
    if (!configFile) {
        Serial.println("Failed to open config file");
        return false;
    }

    DeserializationError error = deserializeJson(cfg, configFile);//读取配置文件并解析
    if (error) {
        Serial.println("Failed to parse config file");
        return false;
    }

    Serial.print("Loaded serverName: ");
    Serial.println(cfg["serverName"].as<char*>());
    Serial.print("Loaded accessToken: ");
    Serial.println(cfg["accessToken"].as<char*>());
    return true;
}

bool saveConfig() {
    cfg["serverName"] = "api.example.com";
    cfg["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98";

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
        Serial.println("Failed to open config file for writing");
        return false;
    }

    serializeJsonPretty(cfg, configFile);//生成json并写入文件
    serializeJsonPretty(cfg, Serial);//打印到串口
    return true;
}

void setup() {
    Serial.begin(115200);
    Serial.println("");
    Serial.println("Mounting FS...");

    if (!SPIFFS.begin()) {
        Serial.println("Failed to mount file system");
        return;
    }

    if (!saveConfig()) {
        Serial.println("Failed to save config");
    } else {
        Serial.println("Config saved");
    }

    if (!loadConfig()) {
        Serial.println("Failed to load config");
    } else {
        Serial.println("Config loaded");
    }
}

void loop() {
}
